package org.glxy.shop.controller;

import org.glxy.shop.dto.InventoryOperationRequest;
import org.glxy.shop.entity.InventoryLog;
import org.glxy.shop.entity.Product;
import org.glxy.shop.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/products/{productId}/inventory")
public class InventoryController {

    @Autowired
    private InventoryService inventoryService;

    // POST /api/products/{id}/inventory - 执行进出库操作
    @PostMapping
    public ResponseEntity<?> operateInventory(
            @PathVariable String productId,
            @RequestBody InventoryOperationRequest request) {
        try {
            Product product = inventoryService.operateInventory(productId, request);
            return ResponseEntity.ok(product);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "库存操作失败");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    // GET /api/products/{id}/inventory-logs - 查询进出库记录
    @GetMapping("/logs")
    public ResponseEntity<Page<InventoryLog>> getInventoryLogs(
            @PathVariable String productId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<InventoryLog> logs = inventoryService.getInventoryLogs(productId, page, size);
        return ResponseEntity.ok(logs);
    }
}